package pay.serviceImpl;


import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pay.common.AllAssetsCache;
import pay.common.AllAssetsDto;
import pay.service.IUserCache;
import pay.utils.JsonUtils;
import pay.utils.RedisCilent;

@Service
public class UserCacheImpl implements IUserCache {

    @Value("${refreshInterval}")
    private Integer  refreshInterval;//投资资产刷新时间间隔。

    private Logger logger = LoggerFactory.getLogger(UserCacheImpl.class);

    static  String USER_ASSET_CACHE  = "USER_ASSET_CACHE_";

    @Override
    public Boolean removeUserAssetCache(Long userId) {
        logger.info("will delete user asset cache in the redis, userId ={}", userId);
        RedisCilent.delKey(USER_ASSET_CACHE + userId);
        return true;
    }

    @Override
    public AllAssetsDto getUserAssetCache(Long userId) {
        logger.info("will read user asset cache in the redis, userId ={}", userId);

        if(RedisCilent.existsKey(USER_ASSET_CACHE + userId) == false){
            return null;
        }

        String cacheMsgStr = RedisCilent.getString(USER_ASSET_CACHE + userId);

        AllAssetsCache allAssetsCache = JsonUtils.toBean(cacheMsgStr, AllAssetsCache.class);

        AllAssetsDto allAssetsDto = new AllAssetsDto();

        if(allAssetsCache != null){
            allAssetsDto = allAssetsCache.toDto();
        }

        return allAssetsDto;
    }

    @Override
    public Boolean setUserAssetCache(Long userId, AllAssetsDto allAssetsDto) {
        logger.info("will set user asset cache in the redis, userId ={}", userId);

        AllAssetsCache allAssetsCache = allAssetsDto.toCache();

        String msgStr = String.valueOf(new JSONObject(allAssetsCache));

        RedisCilent.setString(USER_ASSET_CACHE + userId, msgStr, refreshInterval);

        return true;
    }

}
